<template>
	<div class="content" v-if="dialogVisible">
		<el-dialog title="自定义变量" :visible.sync="dialogVisible" :before-close="onClose" custom-class="add-user-attribute" :destroy-on-close="true" width="500px">
			<el-form :model="userAttr" class="form-wraper" label-width="100px" label-position="left" :rules="rules" ref="AddUserAttribute">
				<el-form-item label="描述" prop="label">
					<el-input v-model="userAttr.label" placeholder="例如：年龄" maxlength="10" @input="e => (userAttr.label = validForbid(e))"></el-input>
				</el-form-item>
				<el-form-item label="变量" prop="value">
					<el-input v-model="userAttr.value" placeholder="例如：年龄" maxlength="10" @input="e => (userAttr.value = validForbid(e))"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="onOk">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	name: 'AddUserAttribute',
	props: {
		variableDict: {
			type: Array,
			default: () => []
		},
		dialogVisible: {
			type: Boolean,
			default: false
		}
	},
	data() {
		let validateVariable = (rule, value, callback) => {
			if (value.length <= 0) {
				callback(new Error('请输入变量'));
				return;
			}
			this.variableDict.map(item => {
				if (item.value === value) {
					callback(new Error('变量已存在，请重新输入'));
					return;
				}
			});
			callback();
		};
		return {
			userAttr: {
				label: '',
				value: ''
			},
			rules: {
				label: [
					{ required: true, message: '请输入描述', trigger: 'blur' },
					{ min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
				],
				value: [
					{ required: true, message: '请输入变量', trigger: 'blur' },
					{ min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
					{ validator: validateVariable, trigger: 'blur' }
				]
			}
		};
	},
	methods: {
		onClose() {
			this.userAttr.label = '';
			this.userAttr.value = '';
			this.$emit('on-cancel');
		},
		onOk() {
			this.$refs['AddUserAttribute'].validate(valid => {
				if (valid) {
					const data = JSON.parse(JSON.stringify(this.userAttr));
					this.$emit('on-ok', data);
					this.userAttr.label = '';
					this.userAttr.value = '';
				} else {
					console.error('error submit!!');
					return false;
				}
			});
		}
	}
};
</script>

<style scoped>
.content {
	display: flex;
	flex-direction: column;
	justify-content: flex-start;
	align-items: flex-start;
	/* width:100px; */
	background: rgba(255, 255, 255, 1);
	box-shadow: 5px 7px 49px 5px rgba(44, 137, 234, 0.13);
}

.form-wraper {
	width: 100%;
}
</style>

<style>
.add-user-attribute .el-dialog__body {
	border-bottom: 1px solid #ccc;
	border-top: 1px solid #ccc;
	display: flex;
}
</style>
